package com.repair.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.repair.entity.RepairOrder;
import com.repair.entity.RepairmanLocation;
import com.repair.mapper.RepairOrderMapper;
import com.repair.service.RepairOrderService;
import com.repair.service.RepairmanLocationService;
import com.repair.service.UserService;
import com.repair.util.BaiduMapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.HashMap;

@Service
public class RepairOrderServiceImpl extends ServiceImpl<RepairOrderMapper, RepairOrder> implements RepairOrderService {

    @Autowired
    private BaiduMapUtil baiduMapUtil;

    @Autowired
    private RepairmanLocationService repairmanLocationService;

    private final RepairOrderMapper repairOrderMapper;

    @Autowired
    private UserService userService;

    public RepairOrderServiceImpl(RepairOrderMapper repairOrderMapper) {
        this.repairOrderMapper = repairOrderMapper;
    }

    @Override
    @Transactional
    public void createOrder(RepairOrder order) {
        if (order.getUserId() == null) {
            throw new RuntimeException("用户ID不能为空");
        }
        
        order.setStatus(0);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        save(order);
    }

    @Override
    @Transactional
    public void acceptOrder(Long orderId, Long repairmanId) {
        RepairOrder order = getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        if (order.getStatus() != 0) {
            throw new RuntimeException("订单状态不正确");
        }

        order.setRepairmanId(repairmanId);
        order.setStatus(1);
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);

        // 更新维修工位置
        RepairmanLocation location = repairmanLocationService.getByRepairmanId(repairmanId);
        if (location != null) {
            order.setLatitude(location.getLatitude());
            order.setLongitude(location.getLongitude());
            updateById(order);
        }
    }

    @Override
    @Transactional
    public void updateOrderStatus(Long orderId, Integer status) {
        RepairOrder order = getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        order.setStatus(status);
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
    }

    @Override
    public List<RepairOrder> getUserOrders(Long userId) {
        return list(new LambdaQueryWrapper<RepairOrder>()
                .eq(RepairOrder::getUserId, userId)
                .eq(RepairOrder::getDeleted, 0)
                .orderByDesc(RepairOrder::getCreateTime));
    }

    @Override
    public List<RepairOrder> getRepairmanOrders(Long repairmanId) {
        return list(new LambdaQueryWrapper<RepairOrder>()
                .eq(RepairOrder::getRepairmanId, repairmanId)
                .eq(RepairOrder::getDeleted, 0)
                .orderByDesc(RepairOrder::getCreateTime));
    }

    @Override
    public List<RepairOrder> getNearbyOrders(Double latitude, Double longitude, Double radius) {
        List<RepairOrder> allOrders = list(new LambdaQueryWrapper<RepairOrder>()
                .eq(RepairOrder::getStatus, 0)
                .eq(RepairOrder::getDeleted, 0));

        return allOrders.stream()
                .filter(order -> {
                    double distance = baiduMapUtil.calculateDistance(
                            latitude, longitude,
                            order.getLatitude(), order.getLongitude()
                    );
                    return distance <= radius;
                })
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void updateRepairmanLocation(Long repairmanId, Double latitude, Double longitude) {
        repairmanLocationService.updateLocation(repairmanId, latitude, longitude);
    }

    @Override
    public long countTodayOrders() {
        LocalDateTime today = LocalDate.now().atStartOfDay();
        return count(new LambdaQueryWrapper<RepairOrder>()
                .ge(RepairOrder::getCreateTime, today));
    }

    @Override
    public long countPendingOrders() {
        return count(new LambdaQueryWrapper<RepairOrder>()
                .eq(RepairOrder::getStatus, 0));
    }

    @Override
    public List<RepairOrder> getRecentOrders() {
        return list(new LambdaQueryWrapper<RepairOrder>()
                .orderByDesc(RepairOrder::getCreateTime)
                .last("LIMIT 10"));
    }

    @Override
    public List<RepairOrder> getOrdersByStatus(Integer status) {
        return list(new LambdaQueryWrapper<RepairOrder>()
                .eq(RepairOrder::getStatus, status)
                .orderByDesc(RepairOrder::getCreateTime));
    }

    @Override
    @Transactional
    public void cancelOrder(Long orderId) {
        RepairOrder order = getById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        if (order.getStatus() != 0 && order.getStatus() != 1) {
            throw new RuntimeException("订单状态不正确");
        }

        order.setStatus(4);
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
    }

    @Override
    public List<Map<String, Object>> getOrderStatistics() {
        return repairOrderMapper.selectOrderStatistics();
    }

    @Override
    public List<Map<String, Object>> getRepairmanStatistics() {
        return repairOrderMapper.selectRepairmanStatistics();
    }

    @Override
    public Map<String, Object> getDashboardData() {
        Map<String, Object> data = new HashMap<>();
        
        // 获取订单状态分布
        List<Map<String, Object>> orderStatus = repairOrderMapper.selectOrderStatus();
        data.put("orderStatus", orderStatus);

        // 获取维修工统计
        List<Map<String, Object>> repairmanStats = repairOrderMapper.selectRepairmanStats();
        data.put("repairmanStats", repairmanStats);

        // 获取待处理订单数
        Long pendingOrders = repairOrderMapper.selectPendingOrdersCount();
        data.put("pendingOrders", pendingOrders);

        // 获取今日订单数
        Long todayOrders = repairOrderMapper.selectTodayOrdersCount();
        data.put("todayOrders", todayOrders);

        // 获取总维修工数
        Long totalRepairmen = userService.countRepairmen();
        data.put("totalRepairmen", totalRepairmen);

        // 总用户数
        Long totalUsers = userService.count();
        data.put("totalUsers", totalUsers);


        return data;
    }

    @Override
    public List<Map<String, Object>> getOrderList() {
        return repairOrderMapper.selectOrderList(null, null);
    }

    @Override
    public Map<String, Object> getOrderDetails(Long id) {
        return repairOrderMapper.selectOrderDetails(id);
    }

    @Override
    public Map<String, Object> getStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取订单趋势（最近30天）
        List<Map<String, Object>> orderTrend = repairOrderMapper.selectOrderTrend();
        statistics.put("orderTrend", orderTrend);

        // 获取维修工绩效
        List<Map<String, Object>> repairmanPerformance = repairOrderMapper.selectRepairmanPerformance();
        statistics.put("repairmanPerformance", repairmanPerformance);

        return statistics;
    }

    @Override
    @Transactional
    public void completeOrder(Long orderId) {
        RepairOrder order = getById(orderId);
        if (order == null || order.getStatus() != 2) {
            throw new RuntimeException("订单状态不正确");
        }

        order.setStatus(3);
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
    }

    @Override
    public List<Map<String, Object>> getPendingOrders() {
        return repairOrderMapper.selectPendingOrders();
    }

    @Override
    public List<Map<String, Object>> getCompletedOrders(Long repairmanId) {
        return repairOrderMapper.selectCompletedOrders(repairmanId);
    }

    @Override
    public List<Map<String, Object>> getAllOrders() {
        return repairOrderMapper.selectOrderList(null, null);
    }

    @Override
    @Transactional
    public void startRepair(Long orderId) {
        RepairOrder order = getById(orderId);
        if (order == null || order.getStatus() != 1) {
            throw new RuntimeException("订单状态不正确");
        }

        order.setStatus(2); // 设置为维修中状态
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
    }

    @Override
    public List<Map<String, Object>> getAcceptedOrders(Long id) {
        return repairOrderMapper.selectAcceptedOrders(id);
    }

    @Override
    public List<Map<String, Object>> getRepairingOrders(Long id) {
        return repairOrderMapper.selectRepairingOrders(id);
    }

    @Override
    public List<Map<String, Object>> getCancelledOrders(Long id) {
        return repairOrderMapper.selectCancelledOrders(id);
    }
} 